<?php
namespace app\user\controller;

use app\common\controller\Front;

class Email extends Front
{
    protected $auth = [
         'check'       => true,
         'none_login'  => '',
         'none_right'  => '*',
         'error_login' => 'user/login/index',
         'error_right' => 'user/login/index',
    ];
    
	public function _initialize()
    {
        $this->request->filter('trim,strip_tags,htmlspecialchars');
        
		parent::_initialize();
        
        if(!str_replace('off','',config('user.captcha_email'))){
            $this->error(lang('error_captcha_disabled'),'user/center/index');
        }
	}
    
	public function index()
    {
		return $this->fetch();
	}
    
    public function notice()
    {
        $userEmail = input('post.user_email');
        if(!is_email($userEmail)){
            $this->error(lang('error_mail'));
        }
        //发送频率限制
        if(!model('user/Captcha','loglic')->interval()){
            $this->error(model('user/Captcha','loglic')->getError());
        }
        //发送验证码
        if(!model('user/Captcha','loglic')->email($this->site['user']['user_id'],$userEmail)){
            $this->error(model('user/Captcha','loglic')->getError());
        }
        //返回结果
        $this->success(lang('success'), 'user/center/index', ['action'=>'notice']);
    }
    
    public function update()
    {
        $post = input('post.');
        $validate = new \think\Validate([
            'user_email'    => 'email',
            'user_captcha'  => 'require',
        ],[
            'user_email.email'     => lang('error_email'),
            'user_captcha.require' => lang('error_captcha_require'),
        ]);
        if(!$validate->check($post)){
            $this->error($validate->getError());
        }
        //验证码验证
        if(!model('user/Captcha','loglic')->checkByUid($this->site['user']['user_id'],$post['user_captcha'],'email')){
            $this->error(model('user/Captcha','loglic')->getError());
        }
        //修改邮箱
        $result = db('user')->update([
            'user_id'    => $this->site['user']['user_id'],
            'user_email' => $post['user_email'],
        ]);
        if(!$result){
            $this->error(db('user')->getError());
        }
        //操作成功
        $this->success(lang('success'), 'user/center/index', ['action'=>'update']);
    }
}